package com.example.spring.boot.spring.hadlermethod;

import com.example.spring.boot.spring.json.JsonUtils;
import com.example.spring.boot.spring.context.CalledContext;
import com.example.spring.boot.spring.response.ResponseStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod;

import java.lang.reflect.Method;

public class MyServletInvocableHandlerMethod extends ServletInvocableHandlerMethod {
    private static Logger logger= LoggerFactory.getLogger(MyServletInvocableHandlerMethod.class);
    public MyServletInvocableHandlerMethod(HandlerMethod handlerMethod) {
        super(handlerMethod);
    }

    @Override
    protected Object doInvoke(Object... args) throws Exception {

        Object result = null;
        Exception ex  = null;
        CalledContext calledContext = new CalledContext();
        ResponseStruct responseStruct = new ResponseStruct();

        logBefore(this.getBean(),this.getMethod(), calledContext,args);
        try {
             result = super.doInvoke(args);
        }catch (Exception e){
            ex = e;
            responseStruct.setCode(500);
        }

        logAfter(calledContext,result,ex);

        responseStruct.setData(result);
        return responseStruct;
    }
    private void logBefore(Object bean, Method method, CalledContext calledContext, Object ...args){
        calledContext.setClassName(bean.getClass().getName());
        calledContext.setMethod(method.getName());
        calledContext.setArgs(args);
        //logger.info("{}",JsonUtils.toString(calledContext));
    }
    private void logAfter(CalledContext calledContext, Object result, Exception ex ) {
        calledContext.setResult(result);
        calledContext.setException(ex);
        if(ex == null){
            logger.info("{}", JsonUtils.toString(calledContext));
        }else{
            logger.error("{}",JsonUtils.toString(calledContext));
        }

    }
}
